const userService = require('../service/user.service')
const errorTypes = require('../constans/error-types')
const md5password = require('../utils/password-handle')

// 验证账号密码中间件
const verifyUser = async (ctx, next) => {
    // 1.获取用户名和密码
    const { userName, password } = ctx.request.body
    // 2.判断用户名或者密码不能空
    if (!userName || !password) {
        const error = new Error(errorTypes.NAME_OR_PASSWORD_IS_REQUIRED);
        return ctx.app.emit('error', error, ctx);
    }
    // 3.判断这次注册的用户名是没有被注册过
    const result = await userService.getUserByName(userName);
    if (result.length) {
        const error = new Error(errorTypes.USER_ALREADY_EXISTS);
        return ctx.app.emit('error', error, ctx);
    }
    await next()
}
// 密码加密
const handlePassword = async (ctx, next) => {
    const { password } = ctx.request.body
    ctx.request.body.password = md5password(password)
    await next()
}

// 验证账号是否存在
const verifyName = async (ctx, next) => {
    // 获取用户名
    const { id } = ctx.request.params
    if (!id) {
        const error = new Error(errorTypes.PARAMSISNULL);
        return ctx.app.emit('error', error, ctx);
    }
    await next()
}

module.exports = {
    verifyUser,
    handlePassword,
    verifyName
}